<template>
  <div class="page-wrap">
    <el-card shadow="never">
      <el-tabs v-model="activeTab">
        <el-tab-pane label="优惠券" name="coupon">
          <div class="toolbar">
            <el-input v-model="couponFilters.search" placeholder="搜索名称" clearable class="w-240" />
            <el-select v-model="couponFilters.status" placeholder="状态" clearable class="w-160">
              <el-option label="全部" value="all" />
              <el-option label="启用" value="active" />
              <el-option label="停用" value="inactive" />
            </el-select>
            <el-button type="primary" @click="openCouponAdd">新增优惠券</el-button>
            <el-button @click="exportCoupons">导出</el-button>
          </div>

          <div class="stats">
            <el-statistic title="在用优惠券" :value="totalActiveCoupons" />
            <el-statistic title="可用促销方案" :value="totalActivePromotions" />
          </div>

          <el-table :data="couponPaged" border stripe>
            <el-table-column prop="name" label="名称" min-width="160" />
            <el-table-column label="类型" width="100">
              <template #default="{ row }">
                <el-tag type="info">{{ row.type === 'amount' ? '满减券' : '折扣券' }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="面值/折扣" width="120">
              <template #default="{ row }">
                <span v-if="row.type==='amount'">¥{{ row.value }}</span>
                <span v-else>{{ (Number(row.value)/10).toFixed(1) }}折</span>
              </template>
            </el-table-column>
            <el-table-column label="门槛" width="120">
              <template #default="{ row }">{{ Number(row.minSpend||0) > 0 ? `满¥${row.minSpend}` : '无门槛' }}</template>
            </el-table-column>
            <el-table-column label="有效期" width="220">
              <template #default="{ row }">{{ row.validFrom }} ~ {{ row.validTo }}</template>
            </el-table-column>
            <el-table-column label="渠道" width="140">
              <template #default="{ row }">{{ (row.channels || []).join('/') }}</template>
            </el-table-column>
            <el-table-column label="已发/配额" width="120">
              <template #default="{ row }">{{ row.issued }}/{{ row.total }}</template>
            </el-table-column>
            <el-table-column prop="used" label="已用" width="100" />
            <el-table-column label="状态" width="100">
              <template #default="{ row }">
                <el-tag :type="row.status==='active' ? 'success' : 'warning'">{{ row.status==='active' ? '启用' : '停用' }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="360" fixed="right">
              <template #default="{ row }">
                <el-button size="small" @click="toggleCoupon(row)">{{ row.status==='active' ? '停用' : '启用' }}</el-button>
                <el-button size="small" @click="openIssue(row)" :disabled="row.status!=='active'">发券</el-button>
                <el-button size="small" @click="openIssuedRecords(row)">记录</el-button>
                <el-button size="small" @click="openCouponEdit(row)">编辑</el-button>
                <el-button size="small" type="danger" @click="deleteCouponRow(row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="pagination">
            <el-pagination
              background
              layout="prev, pager, next, jumper"
              :page-size="couponPage.size"
              :total="couponListFiltered.length"
              v-model:current-page="couponPage.index"
            />
          </div>
        </el-tab-pane>

        <el-tab-pane label="促销方案" name="promotion">
          <div class="toolbar">
            <el-input v-model="promotionFilters.search" placeholder="搜索名称" clearable class="w-240" />
            <el-select v-model="promotionFilters.status" placeholder="状态" clearable class="w-160">
              <el-option label="全部" value="all" />
              <el-option label="启用" value="active" />
              <el-option label="停用" value="inactive" />
            </el-select>
            <el-button type="primary" @click="openPromotionAdd">新增方案</el-button>
            <el-button @click="exportPromotions">导出</el-button>
          </div>

          <el-table :data="promotionPaged" border stripe>
            <el-table-column prop="name" label="名称" min-width="160" />
            <el-table-column prop="ruleType" label="规则类型" width="140">
              <template #default="{ row }">{{ ruleTypeName(row.ruleType) }}</template>
            </el-table-column>
            <el-table-column label="参数" min-width="200">
              <template #default="{ row }">{{ ruleConfigText(row) }}</template>
            </el-table-column>
            <el-table-column label="范围" width="200">
              <template #default="{ row }">{{ scopeText(row) }}</template>
            </el-table-column>
            <el-table-column label="有效期" width="220">
              <template #default="{ row }">{{ row.validFrom }} ~ {{ row.validTo }}</template>
            </el-table-column>
            <el-table-column label="状态" width="100">
              <template #default="{ row }">
                <el-tag :type="row.status==='active' ? 'success' : 'warning'">{{ row.status==='active' ? '启用' : '停用' }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="260" fixed="right">
              <template #default="{ row }">
                <el-button size="small" @click="togglePromotion(row)">{{ row.status==='active' ? '停用' : '启用' }}</el-button>
                <el-button size="small" @click="openPromotionEdit(row)">编辑</el-button>
                <el-button size="small" type="danger" @click="deletePromotionRow(row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="pagination">
            <el-pagination
              background
              layout="prev, pager, next, jumper"
              :page-size="promotionPage.size"
              :total="promotionListFiltered.length"
              v-model:current-page="promotionPage.index"
            />
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 优惠券：新增/编辑 -->
    <el-dialog v-model="couponEditVisible" :title="couponForm.id ? '编辑优惠券' : '新增优惠券'" width="640px">
      <el-form :model="couponForm" :rules="couponRules" ref="couponRef" label-width="100px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="couponForm.name" />
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="couponForm.type">
            <el-option label="满减券" value="amount" />
            <el-option label="折扣券" value="percent" />
          </el-select>
        </el-form-item>
        <el-form-item :label="couponForm.type==='amount' ? '面值(元)' : '折扣(折)'" prop="value">
          <el-input-number v-model="couponForm.value" :min="0" :max="couponForm.type==='amount'?999999:100" />
        </el-form-item>
        <el-form-item label="门槛(元)">
          <el-input-number v-model="couponForm.minSpend" :min="0" />
        </el-form-item>
        <el-form-item label="有效期" prop="validRange">
          <el-date-picker v-model="couponForm.validRange" type="daterange" start-placeholder="开始日期" end-placeholder="结束日期" value-format="YYYY-MM-DD" />
        </el-form-item>
        <el-form-item label="渠道">
          <el-select v-model="couponForm.channels" multiple placeholder="选择渠道">
            <el-option label="POS" value="pos" />
            <el-option label="线上" value="online" />
          </el-select>
        </el-form-item>
        <el-form-item label="配额(张)" prop="total">
          <el-input-number v-model="couponForm.total" :min="0" />
        </el-form-item>
        <el-form-item label="状态">
          <el-switch v-model="couponForm.statusSwitch" active-text="启用" inactive-text="停用" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="couponForm.description" type="textarea" :rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="couponEditVisible=false">取消</el-button>
        <el-button type="primary" @click="onCouponSave">保存</el-button>
      </template>
    </el-dialog>

    <!-- 优惠券：发券 -->
    <el-dialog v-model="issueVisible" title="发放优惠券" width="560px">
      <div class="issue-info">
        <div>优惠券：<strong>{{ currentCoupon?.name }}</strong></div>
        <div>有效期：{{ currentCoupon?.validFrom }} ~ {{ currentCoupon?.validTo }}</div>
        <div>已发/配额：{{ currentCoupon?.issued }}/{{ currentCoupon?.total }}</div>
      </div>
      <el-form :model="issueForm" label-width="100px">
        <el-form-item label="会员">
          <el-select v-model="issueForm.memberId" filterable remote clearable placeholder="搜索姓名/手机号" :remote-method="searchMemberOptions" class="w-320">
            <el-option v-for="m in memberOptions" :key="m.id" :label="`${m.name}（${m.phone}）`" :value="m.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="数量">
          <el-input-number v-model="issueForm.quantity" :min="1" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="issueVisible=false">取消</el-button>
        <el-button type="primary" @click="onIssue">发放</el-button>
      </template>
    </el-dialog>

    <!-- 优惠券：发放记录 -->
    <el-drawer v-model="issuedDrawer" :title="`发放记录 - ${currentCoupon?.name || ''}`" size="50%">
      <el-table :data="currentIssuedRecords" border stripe>
        <el-table-column prop="date" label="时间" width="180" />
        <el-table-column prop="memberName" label="会员" width="120" />
        <el-table-column prop="phone" label="手机号" width="140" />
        <el-table-column prop="quantity" label="数量" width="100" />
        <el-table-column prop="operator" label="操作人" width="120" />
      </el-table>
    </el-drawer>

    <!-- 促销：新增/编辑 -->
    <el-dialog v-model="promotionEditVisible" :title="promotionForm.id ? '编辑促销方案' : '新增促销方案'" width="640px">
      <el-form :model="promotionForm" :rules="promotionRules" ref="promotionRef" label-width="110px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="promotionForm.name" />
        </el-form-item>
        <el-form-item label="规则类型" prop="ruleType">
          <el-select v-model="promotionForm.ruleType">
            <el-option label="满减" value="fullReduction" />
            <el-option label="折扣" value="discount" />
            <el-option label="买赠" value="buyXGetY" />
          </el-select>
        </el-form-item>
        <template v-if="promotionForm.ruleType==='fullReduction'">
          <el-form-item label="满额阈值(元)" prop="ruleConfig.threshold">
            <el-input-number v-model="promotionForm.ruleConfig.threshold" :min="0" />
          </el-form-item>
          <el-form-item label="立减金额(元)" prop="ruleConfig.discount">
            <el-input-number v-model="promotionForm.ruleConfig.discount" :min="0" />
          </el-form-item>
        </template>
        <template v-else-if="promotionForm.ruleType==='discount'">
          <el-form-item label="折扣(折)" prop="ruleConfig.percent">
            <el-input-number v-model="promotionForm.ruleConfig.percent" :min="1" :max="100" />
          </el-form-item>
        </template>
        <template v-else>
          <el-form-item label="买(件)" prop="ruleConfig.buyQty">
            <el-input-number v-model="promotionForm.ruleConfig.buyQty" :min="1" />
          </el-form-item>
          <el-form-item label="送(件)" prop="ruleConfig.getQty">
            <el-input-number v-model="promotionForm.ruleConfig.getQty" :min="1" />
          </el-form-item>
        </template>
        <el-form-item label="适用范围" prop="scopeType">
          <el-radio-group v-model="promotionForm.scopeType">
            <el-radio label="all">全场</el-radio>
            <el-radio label="category">按分类</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="promotionForm.scopeType==='category'" label="参与分类">
          <el-select v-model="promotionForm.categories" multiple placeholder="选择分类">
            <el-option v-for="c in categories" :key="c" :value="c" :label="c" />
          </el-select>
        </el-form-item>
        <el-form-item label="有效期" prop="validRange">
          <el-date-picker v-model="promotionForm.validRange" type="daterange" start-placeholder="开始日期" end-placeholder="结束日期" value-format="YYYY-MM-DD" />
        </el-form-item>
        <el-form-item label="状态">
          <el-switch v-model="promotionForm.statusSwitch" active-text="启用" inactive-text="停用" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="promotionForm.description" type="textarea" :rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="promotionEditVisible=false">取消</el-button>
        <el-button type="primary" @click="onPromotionSave">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { reactive, ref, computed, onMounted } from 'vue'
import { useMarketingStore } from '@/stores/marketing.js'
import { useMemberStore } from '@/stores/member.js'
import { useProductStore } from '@/stores/product.js'

// stores
const marketing = useMarketingStore()
const memberStore = useMemberStore()
const productStore = useProductStore()

// 初始化数据
onMounted(() => {
  marketing.initializeMarketingData()
  if (!memberStore.members.length) memberStore.initializeMembers()
  if (!productStore.productList.length) productStore.initializeProducts()
})

// tabs
const activeTab = ref('coupon')

// categories for promotion scope
const categories = computed(() => productStore.categories)

// ===== 优惠券列表/筛选/分页
const couponFilters = reactive({ search: '', status: 'all' })
const couponListFiltered = computed(() => marketing.getFilteredCoupons(couponFilters))
const couponPage = reactive({ index: 1, size: 10 })
const couponPaged = computed(() => couponListFiltered.value.slice((couponPage.index - 1) * couponPage.size, couponPage.index * couponPage.size))

// stats
const { totalActiveCoupons, totalActivePromotions } = marketing

// edit coupon dialog
const couponEditVisible = ref(false)
const couponRef = ref()
const couponForm = reactive({
  id: '', name: '', type: 'amount', value: 0, minSpend: 0,
  validRange: [], channels: [], total: 0, statusSwitch: false, description: ''
})
const couponRules = {
  name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
  type: [{ required: true, message: '请选择类型', trigger: 'change' }],
  value: [{ required: true, message: '请输入面值/折扣', trigger: 'blur' }],
  total: [{ required: true, message: '请输入配额', trigger: 'blur' }],
  validRange: [{ type: 'array', required: true, message: '请选择有效期', trigger: 'change' }],
}

function openCouponAdd() {
  Object.assign(couponForm, { id: '', name: '', type: 'amount', value: 0, minSpend: 0, validRange: [], channels: [], total: 0, statusSwitch: false, description: '' })
  couponEditVisible.value = true
}
function openCouponEdit(row) {
  Object.assign(couponForm, {
    id: row.id,
    name: row.name,
    type: row.type,
    value: row.value,
    minSpend: row.minSpend,
    validRange: [row.validFrom, row.validTo],
    channels: [...(row.channels || [])],
    total: row.total,
    statusSwitch: row.status === 'active',
    description: row.description || ''
  })
  couponEditVisible.value = true
}
function onCouponSave() {
  couponRef.value.validate(valid => {
    if (!valid) return
    const payload = {
      name: couponForm.name,
      type: couponForm.type,
      value: couponForm.value,
      minSpend: couponForm.minSpend,
      validRange: couponForm.validRange,
      channels: couponForm.channels,
      total: couponForm.total,
      status: couponForm.statusSwitch ? 'active' : 'inactive',
      description: couponForm.description,
    }
    if (couponForm.id) marketing.updateCoupon(couponForm.id, payload)
    else marketing.addCoupon(payload)
    couponEditVisible.value = false
  })
}
function deleteCouponRow(row) { marketing.deleteCoupon(row.id) }
function toggleCoupon(row) { marketing.toggleCouponStatus(row.id) }
function exportCoupons() { marketing.exportCouponsToCSV(couponListFiltered.value) }

// issue coupon
const issueVisible = ref(false)
const issuedDrawer = ref(false)
const currentCoupon = ref(null)
const issueForm = reactive({ memberId: '', quantity: 1 })
const memberOptions = ref([])
const currentIssuedRecords = ref([])

function openIssue(row) {
  currentCoupon.value = row
  Object.assign(issueForm, { memberId: '', quantity: 1 })
  memberOptions.value = []
  issueVisible.value = true
}
function searchMemberOptions(keyword) {
  const list = memberStore.getFilteredMembers({ search: keyword || '', tier: '' })
  memberOptions.value = list.slice(0, 20)
}
function onIssue() {
  if (!issueForm.memberId) return
  const m = memberStore.members.find(x => x.id === issueForm.memberId)
  const res = marketing.issueCoupon(currentCoupon.value.id, m, issueForm.quantity, '系统')
  if (!res.ok) return alert(res.message)
  issueVisible.value = false
}
function openIssuedRecords(row) {
  currentCoupon.value = row
  currentIssuedRecords.value = marketing.getIssuedRecordsByCoupon(row.id)
  issuedDrawer.value = true
}

// ===== 促销列表/筛选/分页
const promotionFilters = reactive({ search: '', status: 'all' })
const promotionListFiltered = computed(() => marketing.getFilteredPromotions(promotionFilters))
const promotionPage = reactive({ index: 1, size: 10 })
const promotionPaged = computed(() => promotionListFiltered.value.slice((promotionPage.index - 1) * promotionPage.size, promotionPage.index * promotionPage.size))

// promotion edit dialog
const promotionEditVisible = ref(false)
const promotionRef = ref()
const promotionForm = reactive({
  id: '', name: '', ruleType: 'fullReduction', ruleConfig: {}, scopeType: 'all', categories: [], validRange: [], statusSwitch: false, description: ''
})
const promotionRules = {
  name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
  ruleType: [{ required: true, message: '请选择规则类型', trigger: 'change' }],
  validRange: [{ type: 'array', required: true, message: '请选择有效期', trigger: 'change' }],
}

function openPromotionAdd() {
  Object.assign(promotionForm, { id: '', name: '', ruleType: 'fullReduction', ruleConfig: {}, scopeType: 'all', categories: [], validRange: [], statusSwitch: false, description: '' })
  promotionEditVisible.value = true
}
function openPromotionEdit(row) {
  Object.assign(promotionForm, {
    id: row.id,
    name: row.name,
    ruleType: row.ruleType,
    ruleConfig: { ...(row.ruleConfig || {}) },
    scopeType: row.scopeType,
    categories: [...(row.categories || [])],
    validRange: [row.validFrom, row.validTo],
    statusSwitch: row.status === 'active',
    description: row.description || ''
  })
  promotionEditVisible.value = true
}
function onPromotionSave() {
  promotionRef.value.validate(valid => {
    if (!valid) return
    // 根据 ruleType 补齐默认字段
    const rc = { ...(promotionForm.ruleConfig || {}) }
    if (promotionForm.ruleType === 'fullReduction') {
      rc.threshold = Number(rc.threshold || 0)
      rc.discount = Number(rc.discount || 0)
    } else if (promotionForm.ruleType === 'discount') {
      rc.percent = Number(rc.percent || 100)
    } else {
      rc.buyQty = Number(rc.buyQty || 1)
      rc.getQty = Number(rc.getQty || 1)
    }
    const payload = {
      name: promotionForm.name,
      ruleType: promotionForm.ruleType,
      ruleConfig: rc,
      scopeType: promotionForm.scopeType,
      categories: promotionForm.scopeType === 'category' ? [...promotionForm.categories] : [],
      validRange: promotionForm.validRange,
      status: promotionForm.statusSwitch ? 'active' : 'inactive',
      description: promotionForm.description,
    }
    if (promotionForm.id) marketing.updatePromotion(promotionForm.id, payload)
    else marketing.addPromotion(payload)
    promotionEditVisible.value = false
  })
}
function togglePromotion(row) { marketing.togglePromotionStatus(row.id) }
function deletePromotionRow(row) { marketing.deletePromotion(row.id) }
function exportPromotions() { marketing.exportPromotionsToCSV(promotionListFiltered.value) }

// helpers
function ruleTypeName(t) {
  return t === 'fullReduction' ? '满减' : (t === 'discount' ? '折扣' : '买赠')
}
function ruleConfigText(row) {
  if (row.ruleType === 'fullReduction') return `满¥${row.ruleConfig?.threshold || 0} - ¥${row.ruleConfig?.discount || 0}`
  if (row.ruleType === 'discount') return `${Number(row.ruleConfig?.percent || 100) / 10} 折`
  return `买${row.ruleConfig?.buyQty || 1}送${row.ruleConfig?.getQty || 1}`
}
function scopeText(row) {
  return row.scopeType === 'all' ? '全场' : `分类：${(row.categories || []).join('/')}`
}
</script>

<style scoped>
.page-wrap { padding: 16px; }
.toolbar { display: flex; gap: 12px; align-items: center; margin-bottom: 12px; }
.w-240 { width: 240px; }
.w-160 { width: 160px; }
.w-320 { width: 320px; }
.stats { display: grid; grid-template-columns: repeat(2, 1fr); gap: 12px; margin-bottom: 12px; }
.pagination { display: flex; justify-content: flex-end; margin-top: 10px; }
.issue-info { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 8px; margin-bottom: 12px; color: #4b5563; }
</style>


